package com.fxf.srb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fxf.common.exception.Assert;
import com.fxf.common.result.ResponseEnum;
import com.fxf.common.util.MD5;
import com.fxf.srb.base.util.JwtUtils;
import com.fxf.srb.core.mapper.UserAccountMapper;
import com.fxf.srb.core.mapper.UserLoginRecordMapper;
import com.fxf.srb.core.pojo.UserInfoQuery;
import com.fxf.srb.core.pojo.entity.UserAccount;
import com.fxf.srb.core.pojo.entity.UserInfo;
import com.fxf.srb.core.mapper.UserInfoMapper;
import com.fxf.srb.core.pojo.entity.UserLoginRecord;
import com.fxf.srb.core.pojo.vo.LoginVo;
import com.fxf.srb.core.pojo.vo.RegisterVO;
import com.fxf.srb.core.pojo.vo.UserIndexVO;
import com.fxf.srb.core.pojo.vo.UserInfoVo;
import com.fxf.srb.core.service.IUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 用户基本信息 服务实现类
 * </p>
 *
 * @author fxf
 * @since 2021-05-26
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    @Resource
    private UserAccountMapper userAccountMapper;

    @Resource
    private UserLoginRecordMapper userLoginRecordMapper;

    @Transactional( rollbackFor = {Exception.class})
    @Override
    public void register(RegisterVO registerVO) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",registerVO.getMobile());
        Integer count = baseMapper.selectCount(wrapper);

        Assert.isTrue(count == 0, ResponseEnum.MOBILE_EXIST_ERROR);

        UserInfo userInfo = new UserInfo();
        userInfo.setUserType(registerVO.getUserType());
        userInfo.setNickName(registerVO.getMobile());
        userInfo.setName(registerVO.getMobile());
        userInfo.setMobile(registerVO.getMobile());

        userInfo.setPassword(MD5.encrypt(registerVO.getPassword()));
        baseMapper.insert(userInfo);

        //创建会员账户
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userInfo.getId());
        userAccountMapper.insert(userAccount);


    }

    @Transactional( rollbackFor = {Exception.class})
    @Override
    public UserInfoVo login(LoginVo loginVo, String ip) {

        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
        Integer userType = loginVo.getUserType();

        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        wrapper.eq("use_type",userType);
        UserInfo userInfo = baseMapper.selectOne(wrapper);

        //校验用户信息是否正确
        Assert.notNull(userInfo,ResponseEnum.LOGIN_MOBILE_ERROR);
        //校验用户是否被锁定
        Assert.equals(userInfo.getStatus(),UserInfo.STATUS_NORMAL,ResponseEnum.LOGIN_LOKED_ERROR);

        //记录用户登录日志
        UserLoginRecord userLoginRecord = new UserLoginRecord();
        userLoginRecord.setIp(ip);
        userLoginRecord.setUserId(userInfo.getId());
        userLoginRecordMapper.insert(userLoginRecord);

        //颁发token令牌
        String token = JwtUtils.createToken(userInfo.getId(), userInfo.getName());
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setName(userInfo.getName());
        userInfoVo.setMobile(userInfo.getMobile());
        userInfoVo.setHeadImg(userInfo.getHeadImg());
        userInfoVo.setToken(token);
        userInfoVo.setNickName(userInfo.getNickName());

        return userInfoVo;
    }

    @Override
    public IPage<UserInfo> listPage(Page<UserInfo> pageParam, UserInfoQuery userInfoQuery) {
        String mobile = userInfoQuery.getMobile();
        Integer userType = userInfoQuery.getUserType();
        Integer status = userInfoQuery.getStatus();

        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();

        if (userInfoQuery == null){
            return baseMapper.selectPage(pageParam, null);
        }
        wrapper.eq(StringUtils.isNotBlank(mobile),"mobile",mobile)
                .eq(status != null,"status",userInfoQuery.getStatus())
                .eq(userType != null,"user_type",userType);
        return baseMapper.selectPage(pageParam,wrapper);
    }

    @Override
    public void lock(Long id, Integer status) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setStatus(status);
        baseMapper.updateById(userInfo);
    }

    /**
     * 校验手机号是否已经注册
     * @param mobile
     * @return
     */
    @Override
    public boolean checkMobile(String mobile) {

        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        Integer count = baseMapper.selectCount(wrapper);
        return count > 0;
    }

    @Override
    public UserIndexVO getIndexUserInfo(Long userId) {
        UserIndexVO userIndexVO = new UserIndexVO();

        //用户信息
        UserInfo userInfo = baseMapper.selectById(userId);

        //用户账户信息
        QueryWrapper<UserAccount> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        UserAccount userAccount = userAccountMapper.selectOne(wrapper);

        //用户登录信息
        QueryWrapper<UserLoginRecord> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("user_id",userId).orderByAsc("id").last("limit 1");
        UserLoginRecord userLoginRecord = userLoginRecordMapper.selectOne(wrapper1);

        userIndexVO.setUserId(userId);
        userIndexVO.setName(userInfo.getName());
        userIndexVO.setNickName(userInfo.getNickName());
        userIndexVO.setUserType(userInfo.getUserType());
        userIndexVO.setHeadImg(userInfo.getHeadImg());
        userIndexVO.setBindStatus(userInfo.getBindStatus());
        userIndexVO.setAmount(userAccount.getAmount());
        userIndexVO.setFreezeAmount(userAccount.getFreezeAmount());
        userIndexVO.setLastLoginTime(userLoginRecord.getCreateTime());

        return userIndexVO;
    }

    @Override
    public String getMobileByBindCode(String bindCode) {
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("bind_code", bindCode);
        UserInfo userInfo = baseMapper.selectOne(userInfoQueryWrapper);
        return userInfo.getMobile();
    }


}
